package com.beep.erp.model.addinstock;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.beep.erp.Constants;
import com.beep.erp.R;
import com.beep.erp.common.base.ToolbarActivity;
import com.beep.erp.common.bean.BizStorageLocationsListBean;
import com.beep.erp.common.bean.StockListBean;
import com.beep.erp.common.dialog.AddStockDialog;
import com.beep.erp.common.rx.RxBus;
import com.beep.erp.common.utils.MD5util;
import com.beep.erp.common.utils.SPUtils;
import com.beep.erp.common.utils.TimeUtils;
import com.beep.erp.common.utils.ToastUtils;
import com.beep.erp.common.utils.ToolsUtils;
import com.beep.erp.common.widget.recyclerview.divider.HorizontalDividerItemDecoration;
import com.beep.erp.common.widget.refresh.RefreshView;
import com.beep.erp.common.widget.refresh.container.DefaultHeader;
import com.beep.erp.common.widget.tips.TipsHelper;
import com.beep.erp.model.purchase.PurchaseListFragment;
import com.beep.erp.model.stockdetail.StockDetailContract;
import com.beep.erp.model.stockdetail.StockDetailModel;
import com.beep.erp.model.stockdetail.StockDetailPresenter;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.beep.erp.AppContext._context;

/**
 * 添加入库单
 */
public class InStockActivity extends ToolbarActivity<StockDetailPresenter, StockDetailModel> implements StockDetailContract.View, RefreshView.OnFreshListener,
        InStockGoodsListAdapter.OnItemClickLitener {
    private static final String PURCHASEID = "purchaseId:";
    private static final int REQUEST_EDIT_CODE = 10;

    @BindView(R.id.appbatlayout)
    AppBarLayout appbatlayout;
    @BindView(R.id.rl_instock)
    RecyclerView rlInstock;
    @BindView(R.id.super_refresh)
    RefreshView superRefresh;
    @BindView(R.id.activity_invite)
    CoordinatorLayout activityInvite;
    @BindView(R.id.tv_right)
    TextView tvRight;

    TipsHelper mTipsHelper;
    private ArrayList<StockListBean.BizPurchaseDetailVoListBean> mListBeen = new ArrayList<>();
    private ArrayList<BizStorageLocationsListBean.BizStorageLocationsBean> mLocationBeen = new ArrayList<>();
    private InStockGoodsListAdapter mStockListAdapter;

    public static void start(Context context, String purchaseId) {
        Intent intent = new Intent(context, InStockActivity.class);
        intent.putExtra(PURCHASEID, purchaseId);
        context.startActivity(intent);
    }

    @Override
    protected boolean isBack() {
        return true;
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_intstock_goods;
    }

    @Override
    protected void initView() {
        getTvTitle().setText(R.string.add_instock);
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("保存");

        mTipsHelper = createTipsHelper(superRefresh);
        //refreshView下拉刷新 上拉加载
        superRefresh.setListener(this);
        superRefresh.setHeader(new DefaultHeader(this, true));
        //mInviteAdapter recycleview适配器
        mStockListAdapter = new InStockGoodsListAdapter(this, mListBeen);
        //设置为纵向
        rlInstock.setLayoutManager(new LinearLayoutManager(this));
        //必写
        rlInstock.setHasFixedSize(true);
        //添加分割线
        rlInstock.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).build());
        //setAdapter  rlv_mine_invite 这儿用new HeaderAndFooterRecyclerViewAdapter(mInviteAdapter) 是 添加了头布局 直接 写setAdapter(mInviteAdapter)
        rlInstock.setAdapter(mStockListAdapter);

        mStockListAdapter.setOnItemClickLitener(this);

    }

    @Override
    public void getDate() {
        mListBeen.clear();
        mLocationBeen.clear();
        mTipsHelper.hideEmptyType();
        mTipsHelper.hideError();
        mTipsHelper.showLoading(true);
        getStockDetail();
        getBizStorageLocationList();
    }

    private void getBizStorageLocationList() {
        long mills = TimeUtils.getCurTimeMills();

        Map<String, String> map = new HashMap<>();
        map.put("type", "1");
        mPresenter.getBizStorageLocationList(MD5util.MD5Encode(ToolsUtils.buildSignStr(map, mills)), mills + "", "1");
    }

    private void getStockDetail() {
        long mills = TimeUtils.getCurTimeMills();

        Map<String, String> map = new HashMap<>();
        map.put("purchaseId", getIntent().getStringExtra(PURCHASEID));
        mPresenter.getStockDetail(MD5util.MD5Encode(ToolsUtils.buildSignStr(map, mills)), mills + "", getIntent().getStringExtra(PURCHASEID));
    }

    @Override
    public void getStockDetail(StockListBean stockListBean) {
        //请求成功
        mListBeen.addAll(stockListBean.getBizPurchaseDetailVoList());
        mStockListAdapter.notifyDataSetChanged();
        if (stockListBean.getBizPurchaseDetailVoList().isEmpty()) {
            mTipsHelper.showEmptyType(getString(R.string.emptymessage15));
        }
    }

    @Override
    public void getBizStorageLocationList(BizStorageLocationsListBean bizStorageLocationsListBean) {
        mLocationBeen.addAll(bizStorageLocationsListBean.getBizStorageLocations());
    }

    @Override
    public void saveInstock() {
        PurchaseListFragment.isRefresh = true;
        ToastUtils.showShort(getString(R.string.instock_add_success));
        finish();
    }

    @Override
    public void showLoading() {
        showWaitDialog(getString(R.string.optoning));
    }

    @Override
    public void hideLoading() {
        hideWaitDialog();
        mTipsHelper.hideLoading();
        mTipsHelper.hideEmptyType();
        mTipsHelper.hideEmpty();
        mTipsHelper.hideError();
        superRefresh.onFinishFreshAndLoad();
    }

    @Override
    public void showMessage(String message) {
        ToastUtils.showShort(message);
    }

    //刷新
    @Override
    public void onRefresh() {
        getDate();
    }

    @Override
    public void onLoadmore() {

    }

    @OnClick({R.id.tv_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right:
                SPUtils spUtils = new SPUtils(_context, Constants.EXTRA_LOGIN_SP);
                String userId = spUtils.getString(Constants.USER_ID);
                String userName = spUtils.getString(Constants.EXTRA_NAME);
                SaveStockBody saveStockBody = new SaveStockBody();
                saveStockBody.setPurchaseId(getIntent().getStringExtra(PURCHASEID));
                saveStockBody.setCreateById(userId);
                saveStockBody.setCreateByName(userName);
                saveStockBody.setBizStockInDetailFormList(mListBeen);

                long mills = TimeUtils.getCurTimeMills();
                Map<String, String> map = new HashMap<>();
                map.put("purchaseId", getIntent().getStringExtra(PURCHASEID));
                map.put("createById", userId);
                try {
                    map.put("createByName", URLEncoder.encode(userName, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                mPresenter.saveInstock(MD5util.MD5Encode(ToolsUtils.buildSignStr(map, mills)), mills + "", saveStockBody);
                break;
        }
    }

    @Override
    public void onItemClick(View view, int position) {
       /* Intent intent = new Intent(this, EditStockActivity.class);
        startActivityForResult(intent, REQUEST_EDIT_CODE);*/

        AddStockDialog addStockDialog = new AddStockDialog(this);
        addStockDialog.showDialog(true, mListBeen.get(position).getDifferentAmount(), mLocationBeen, mListBeen.get(position).getType().equals("01"));
        addStockDialog.setOnFullClickListener((goodNum, date, locationId, remark) -> {
            mListBeen.get(position).setActualAmount(goodNum);
            mListBeen.get(position).setManufactureDate(date);
            mListBeen.get(position).setStorageLocationId(locationId);
            mListBeen.get(position).setRemarks(remark);
            mStockListAdapter.notifyDataSetChanged();
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_EDIT_CODE:
                    if (data != null) {
                        String goodsNum = data.getStringExtra(KEY_GOODS_NUM);
                        String goodsLife = data.getStringExtra(KEY_GOODS_LIFE);
                        String goodsProductDate = data.getStringExtra(KEY_GOODS_PRODUCT_DATE);

                        mListBeen.get(pos).setActualAmount(goodsNum);
                        mListBeen.get(pos).setExpirationDate(goodsLife);
                        mListBeen.get(pos).setManufactureDate(goodsProductDate);
                        mStockListAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }*/
    }
}
